package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    @Qualifier("minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;

    @Value("${file.minio.readPath}")
    String readPath;



    //生成静态页的方法
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //先获取模板对象
            Template template = configuration.getTemplate("article.ftl");
            //准备替换模板的数据
            Map params = new HashMap<>();
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId",apAuthor.getUserId());
            params.put("article",apArticle);
            params.put("content", JSON.parseArray(content,Map.class));
            //替换模板生成静态页
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            //将静态页上传到minIO中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String minioPath = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //将静态页在minio中的路径设置到article的static_url字段上
            apArticle.setStaticUrl(minioPath);
            apArticleMapper.updateById(apArticle);
            log.info("成功生成 文章静态页  地址：{}",readPath + minioPath);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败  原因：{}" ,e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }
    }
}
